<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="产品名称" prop="productId">
        <el-select v-model="queryParams.productId" placeholder="请选择产品名称" clearable filterable  style="width: 260px;">
          <el-option
            v-for="item in Product"
            :key="item.id"
            :label="item.productName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 260px;">
          <el-option value="0" label="待开始">待开始</el-option>
          <el-option value="1" label="进行中">进行中</el-option>
          <el-option value="2" label="已完成">已完成</el-option>
          <el-option value="3" label="已取消">已取消</el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="车间名称" prop="workshopId">
        <el-select v-model="queryParams.workshopId" placeholder="请选择车间名称" clearable filterable style="width: 260px;">
          <el-option
            v-for="item in Workshop"
            :key="item.id"
            :label="item.workshopName"
            :value="item.id"
          />
        </el-select>
      </el-form-item><br/>
      <el-form-item label="审核状态" prop="statusSh">
        <el-select v-model="queryParams.statusSh" placeholder="请选择审核状态" clearable style="width: 260px;">
          <el-option value="0" label="待审核">待审核</el-option>
          <el-option value="3" label="审核通过">审核通过</el-option>
          <el-option value="6" label="审核拒绝">审核拒绝</el-option>
        </el-select>
      </el-form-item>
      <el-form-item style="margin-left: 60px">
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:ProductionOrder:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:ProductionOrder:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="ProductionOrderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
<!--      <el-table-column label="主键ID" align="center" prop="id" />-->
      <el-table-column label="生产工单编号" align="center" prop="code" width="190"  show-overflow-tooltip/>
      <el-table-column label="产品编码" align="center" prop="productCode" width="190"/>
      <el-table-column label="产品名称" align="center" prop="productName" width="130"/>
      <el-table-column label="计划数量" align="center" prop="plannedQuantity" />
      <el-table-column label="实际数量" align="center" prop="actualQuantity" />
      <el-table-column label="计划开始时间" align="center" prop="plannedStartTime" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.plannedStartTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="计划结束时间" align="center" prop="plannedEndTime" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.plannedEndTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="审核状态" align="center" prop="statusSh">
        <template slot-scope="scope">
          <span v-if="scope.row.statusSh === '0'">待审核</span>
          <span v-else-if="scope.row.statusSh === '3'">审核通过</span>
          <span v-else-if="scope.row.statusSh === '6'">审核拒绝</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" >
        <template slot-scope="scope">
          <span v-if="scope.row.status === 0">待开始</span>
          <span v-else-if="scope.row.status === 1">进行中</span>
          <span v-else-if="scope.row.status === 2">已完成</span>
          <span v-else-if="scope.row.status === 3">已取消</span>
        </template>
      </el-table-column>
      <el-table-column label="车间名称" align="center" prop="workshopName" width="120" />
      <el-table-column label="备注" align="center" prop="remark" width="120" show-overflow-tooltip/>
      <el-table-column label="操作" align="left" class-name="small-padding fixed-width" width="220" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="getShow(scope.row)"
            v-hasPermi="['system:ProductionOrder:query']"
          >查看</el-button>
          <el-button
            size="mini"
            type="text"
            v-if="scope.row.statusSh !=3"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:ProductionOrder:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-check"
            v-if="scope.row.statusSh !=3"
            @click="statusUpdate(scope.row)"
          >审核</el-button>
          <el-button
            style="color: red"
            size="mini"
            type="text"
            v-if="scope.row.statusSh !=3"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:ProductionOrder:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            v-if="scope.row.statusSh ==3 && scope.row.status==0"
            icon="el-icon-plus"
            @click="ProductionOrder(scope.row)"
            v-hasPermi="['system:ProductionOrder:edit']"
          >生产</el-button>
          <el-button
            size="mini"
            type="text"
            v-if="scope.row.statusSh ==3 && scope.row.status==1"
            icon="el-icon-check"
            @click="ProductionOrderWCSC(scope.row)"
            v-hasPermi="['system:ProductionOrder:edit']"
          >完成生产</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改生产工单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-form-item label="产品名称" prop="productId">
          <el-select v-model="form.productId" placeholder="请选择产品名称" style="width: 450px">
            <el-option
              v-for="index in Product"
              :key="index.id"
              :label="index.productName"
              :value="index.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="计划数量" prop="plannedQuantity">
          <el-input v-model="form.plannedQuantity" placeholder="请输入计划数量" />
        </el-form-item>
        <el-form-item label="车间名称" prop="workshopId">
          <el-select v-model="form.workshopId" placeholder="请选择车间名称" style="width: 450px">
            <el-option
              v-for="index in WorkshopNum"
              :key="index.id"
              :label="index.workshopName"
              :value="index.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="计划开始时间" prop="plannedStartTime">
          <el-date-picker clearable
            v-model="form.plannedStartTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择计划开始时间"
            style="width: 450px">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="计划结束时间" prop="plannedEndTime">
          <el-date-picker clearable
            v-model="form.plannedEndTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择计划结束时间"
            style="width: 450px">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="title" :visible.sync="openWorkshop" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-form-item label="车间名称" prop="workshopId">
          <el-select v-model="form.workshopId" placeholder="请选择车间名称" style="width: 450px">
            <el-option
              v-for="index in WorkshopNum"
              :key="index.id"
              :label="index.workshopName"
              :value="index.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormWorkshop">确 定</el-button>
        <el-button @click="cancelWorkshop">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="title" :visible.sync="open1" width="1000px" append-to-body>
      <div style="display: inline-block;border: 1px gainsboro solid;padding: 10px 10px 10px 30px">
        <div style="display: inline-block;width: 300px;"><p>生产工单编号：{{this.ProductionOrderShow.code}}</p></div>
        <div style="display: inline-block;width: 300px;"><p>产品名称：{{this.ProductionOrderShow.productName}}</p></div>
        <div style="display: inline-block;width: 300px;"><p>车间名称：{{this.ProductionOrderShow.workshopName}}</p></div>
        <div style="display: inline-block;width: 300px;"><p>计划数量：{{this.ProductionOrderShow.plannedQuantity}}</p></div>
        <div style="display: inline-block;width: 300px;" v-if="this.ProductionOrderShow.actualQuantity != null"><p>实际数量：{{this.ProductionOrderShow.actualQuantity}}</p></div>
        <div style="display: inline-block;width: 300px;"><p>计划开始时间：{{this.ProductionOrderShow.plannedStartTime}}</p></div>
        <div style="display: inline-block;width: 300px;"><p>计划结束时间：{{this.ProductionOrderShow.plannedEndTime}}</p></div>
        <div style="display: inline-block;width: 300px;" v-if="this.ProductionOrderShow.actualStartTime != null"><p>实际开始时间：{{this.ProductionOrderShow.actualStartTime}}</p></div>
        <div style="display: inline-block;width: 300px;" v-if="this.ProductionOrderShow.actualEndTime != null"><p>实际结束时间：{{this.ProductionOrderShow.actualEndTime}}</p></div>
        <div style="display: inline-block;width: 300px;"><p>审核状态：{{this.ProductionOrderShow.statusSh == 0 ? '待审核' : this.ProductionOrderShow.statusSh == 3 ? '审核通过' : '审核未通过'}}</p></div>
        <div style="display: inline-block;width: 300px;"><p>状态：{{this.ProductionOrderShow.status == 0 ? '待开始' : this.ProductionOrderShow.status == 1 ? '进行中' : this.ProductionOrderShow.status == 2 ? '已完成' : '已取消'}}</p></div>
        <div style="display: inline-block;width: 300px;"><p>创建时间：{{ parseTime(this.ProductionOrderShow.createTime, '{y}-{m}-{d}') }}</p></div>
        <div style="display: inline-block;width: 300px;"><p>创建人：{{this.ProductionOrderShow.createBy}}</p></div>
        <div style="display: inline-block;width: 300px;" v-if="this.ProductionOrderShow.refuseReason != null && this.ProductionOrderShow.refuseReason != ''"><p>拒绝原因：{{ this.ProductionOrderShow.refuseReason}}</p></div>
        <div style="display: inline-block;width: 300px;" v-if="this.ProductionOrderShow.approveBy != null"><p>审核人：{{this.ProductionOrderShow.approveBy}}</p></div>
        <div style="display: inline-block;width: 300px;" v-if="this.ProductionOrderShow.approveTime != null"><p>审核时间：{{ parseTime(this.ProductionOrderShow.approveTime, '{y}-{m}-{d}') }}</p></div>
        <div style="display: inline-block;width: 300px;"><p>备注：{{this.ProductionOrderShow.remark}}</p></div>
      </div>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button type="success" style="background: #1890ff;border: 1px #1890ff solid" @click="submitFormStatus(3)" v-if="this.title == '审核生产工单'">审核通过</el-button>
        <el-button type="danger" @click="submitFormStatus(6)" v-if="this.title == '审核生产工单'&&this.form.statusSh!=6">审核拒绝</el-button>
        <el-button @click="cancelSh">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 拒绝原因 -->
    <el-dialog :title="title" :visible.sync="refuseOpen" width="500px" append-to-body>
      <el-form ref="refuseForm" :model="refuseForm" :rules="refuseRules" label-width="80px">
        <el-form-item label="拒绝原因" prop="reason">
          <el-input type="textarea" v-model="refuseForm.reason" placeholder="请输入拒绝原因" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button type="primary" @click="refuseSubmit">确 定</el-button>
        <el-button @click="cancelOne">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listProductionOrder, getProductionOrder, delProductionOrder, addProductionOrder, updateProductionOrder } from "@/api/system/ProductionOrder";
import { listProduct } from "@/api/system/Product";
import { listWorkshop } from "@/api/system/Workshop";
import {listProductionPicking} from '@/api/system/ProductionPicking'
import {updateWorkshop} from '@/api/system/Workshop'
import { getInfo } from '@/api/login'

function formatDateToBackend(date) {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
}
export default {
  name: "ProductionOrder",
  data() {
    return {
      //拒绝原因
      refuseOpen:false,
      //拒绝原因
      refuseForm: {
        reason: null
      },
      refuseRules: {
        reason: [
          { required: true, message: "拒绝原因不能为空", trigger: "blur" }
        ]
      },
      statusColor:"rgb(100, 100, 100)",
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 生产工单表格数据
      ProductionOrderList: [],
      //查看
      ProductionOrderShow:[],
      //成品
      Product:[],
      //车间
      Workshop:[],
      //领料
      ProductionPicking:[],
      WorkshopNum:[],
      //id
      ProductionOrderID:[],
      //存储车间存在的数据
      WorkshopCZ:[],
      user:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      open1: false,
      openWorkshop:false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        productId: null,
        status: null,
        workshopId: null,
      },
      query: {
        employ: 1,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        productId: [
          { required: true, message: "产品不能为空", trigger: "blur" }
        ],
        workshopId: [
          { required: true, message: "车间不能为空", trigger: "blur" }
        ],
        plannedQuantity: [
          { required: true, message: "计划数量不能为空", trigger: "blur" }
        ],
        plannedStartTime: [
          { required: true, message: "计划开始时间不能为空", trigger: "blur" }
        ],
        plannedEndTime: [
          { required: true, message: "计划完成时间不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "状态不能为空", trigger: "change" }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getProduct();
    this.getWorkshop();
    this.getWorkshopNum();
    this.getProductionPicking();
    //获取登录进来的用户信息
    this.getUser();
  },
  methods: {

    // 取消按钮
    cancelOne() {
      this.refuseOpen = false;
      this.refuseForm =  { reason: null }
    },
    cancelWorkshop(){
      this.openWorkshop = false;
    },
    cancelSh(){
      this.open1 = false;
    },
    //审批按钮
    statusUpdate(row){
      this.reset();
      const id = row.id || this.ids
      getProductionOrder(id).then(response => {
        this.form = response.data;
        this.ProductionOrderShow = response.data;
        this.open1=true;
        this.title = "审核生产工单";
      });

      if (row.statusSh==0){
        this.statusColor = "rgb(100, 100, 100)";
      }else if (row.statusSh==3){
        this.statusColor = "rgb(82, 196, 26)";
      }else {
        this.statusColor = "rgb(255, 0, 0)";
      }
    },

    /** 查询生产工单列表 */
    getList() {
      this.loading = true;
      this.ProductionOrderID=[];
      var list=[];
      listProductionOrder(this.queryParams).then(response => {
        this.ProductionOrderList = response.rows;
        list=response.rows;
        console.log(list)
        for (var i=0;i<list.length;i++) {
          this.ProductionOrderID.push(list[i].id);
        }
        this.total = response.total;
        this.loading = false;
      });
    },
    //成品
    getProduct() {
      this.loading = true;
      listProduct(this.queryParams).then(response => {
        this.Product = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    //车间
    getWorkshop() {
      this.loading = true;
      listWorkshop(this.queryParams).then(response => {
        this.Workshop = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    //车间
    getWorkshopNum() {
      this.loading = true;
      listWorkshop(this.query).then(response => {
        this.WorkshopNum = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    //领料
    getProductionPicking() {
      this.loading = true;
      listProductionPicking({}).then(response => {
        this.ProductionPicking = response.rows;
        this.loading = false;
      });
    },
    //查询当前登录的用户信息
    getUser() {
      this.loading = true;
      getInfo().then(response => {
        this.user = response.user;
        this.loading = false;
      });
    },
    /** 查询详情*/
    getShow(row) {
      this.loading = true;
      const id = row.id || this.ids
      getProductionOrder(id).then(response => {
        this.ProductionOrderShow = response.data;
        this.open1=true;
        this.loading = false;
        this.title = "查看";
      });
      if (row.status==0){
        this.statusColor = "rgb(100, 100, 100)";
      }else if (row.status==3){
        this.statusColor = "rgb(82, 196, 26)";
      }else {
        this.statusColor = "rgb(255, 0, 0)";
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        code: null,
        productId: null,
        productCode: null,
        productName: null,
        plannedQuantity: null,
        actualQuantity: null,
        plannedStartTime: null,
        plannedEndTime: null,
        actualStartTime: null,
        actualEndTime: null,
        status: null,
        statusSh:null,
        workshopId: null,
        workshopName: null,
        remark: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        approveTime:  null,
        approveBy:  null,
        refuseReason: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加生产工单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getProductionOrder(id).then(response => {
        this.form = response.data;
        this.form.status= this.form.status.toString();
        this.open = true;
        this.title = "修改生产工单";
      });
    },
    ProductionOrder(row){
      this.WorkshopCZ = row;
      //判断车间是否使用中
      for (var j=0;j<this.Workshop.length;j++){
        if (this.Workshop[j].id==row.workshopId && this.Workshop[j].employ==2){
          this.$modal.confirm('该车间正在生产中，是否更换车间生产').then(() => {
            //判断是否还有空闲车间
            if (this.WorkshopNum.length==0){
              this.$modal.msgError("已没有空闲车间");
              return false;
            }
            this.openWorkshop=true;
          }).catch(() => {});
        }
      }
      if(this.ProductionPicking.length === 0){
        this.$modal.msgError("生产工单编号为"+row.code+"的产品未完成领料");
        return false;
      }
      for (var i=0;i<this.ProductionPicking.length;i++){
        if (this.ProductionPicking[i].orderId==row.id && this.ProductionPicking[i].status==1){
          this.form.id=row.id;
          this.form.status=1;
          this.form.actualStartTime=formatDateToBackend(new Date());
          updateProductionOrder(this.form).then(response => {
            this.$modal.msgSuccess("生产工单编号为"+row.code+"的产品开始生产");
            this.getList();
          });
          this.reset();
          this.form.id=row.workshopId;
          this.form.employ=2;
          updateWorkshop(this.form).then(response => {
            this.getWorkshop();
            this.getWorkshopNum();
          })
          return false;
        }
      }
      for (var k=0;k<this.ProductionPicking.length;k++){
        if (this.ProductionPicking[k].orderId!=row.id){
          this.$modal.msgError("生产工单编号为"+row.code+"的产品未完成领料");
          return false;
        }
      }
      return true;
    },
    ProductionOrderWCSC(row){
      this.form.id=row.workshopId;
      this.form.employ=1;
      updateWorkshop(this.form).then(response => {
        this.getWorkshop();
        this.getWorkshopNum();
      })
      this.reset();
      this.form.id=row.id;
      this.form.actualQuantity = row.plannedQuantity;
      this.form.actualEndTime = formatDateToBackend(new Date());
      this.form.status = 2;
      updateProductionOrder(this.form).then(response => {
        this.$modal.msgSuccess("生产工单编号为"+row.code+"的产品完成生产");
        this.getList();
      });
    },
    submitFormStatus(statusSh){
      if (statusSh==6){
        // this.open = false;
        this.refuseOpen=true
      }else {
        this.form.statusSh = statusSh;
        this.form.approveBy = this.user.userName;
        this.form.refuseReason = '';
        this.form.approveTime = formatDateToBackend(new Date());
        updateProductionOrder(this.form).then(response => {
          if (statusSh == 3) {
            this.$modal.msgSuccess("审核成功");
          }
          this.open1 = false;
          this.getList();
        });
      }
    },
    submitFormWorkshop(){
      this.form.id=this.WorkshopCZ.id;
      for (let i=0;i<this.Workshop.length;i++){
        if (this.form.workshopId===this.Workshop[i].id){
          this.form.workshopCode=this.Workshop[i].workshopCode
          this.form.workshopName=this.Workshop[i].workshopName
        }
      }
      updateProductionOrder(this.form).then(response => {
        this.$modal.msgSuccess("修改成功");
        this.openWorkshop = false;
        this.getList();
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateProductionOrder(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            //判断是否为数字
            if (!/^[0-9]*$/.test(this.form.plannedQuantity)){
              this.$modal.msgError("计划数量只能为整数");
              return;
            }
            for (let i=0;i<this.Product.length;i++){
              if (this.form.productId===this.Product[i].id){
                this.form.productCode=this.Product[i].productCode
                this.form.productName=this.Product[i].productName
              }
            }
            for (let i=0;i<this.Workshop.length;i++){
              if (this.form.workshopId===this.Workshop[i].id){
                this.form.workshopCode=this.Workshop[i].workshopCode
                this.form.workshopName=this.Workshop[i].workshopName
              }
            }
            const newId = generateUniqueId(this.ProductionOrderID);
            var orderCode = getOrderCode(this.ProductionOrderList);
            this.form.id = newId;
            this.form.code = orderCode;
            this.form.statusSh=0;
            this.form.status=0;
            addProductionOrder(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    //拒绝原因
    refuseSubmit() {
      this.$refs["refuseForm"].validate(valid => {
        if (valid) {
          this.form.statusSh=6;
          this.form.approveBy=this.user.userName;
          this.form.refuseReason=this.refuseForm.reason
          this.form.approveTime=formatDateToBackend(new Date());
          updateProductionOrder(this.form).then(response => {
            this.$modal.msgError("审批拒绝");
            this.refuseOpen = false;
            this.open1 = false;
            this.getList();
          });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除生产工单编号为"' + ids + '"的数据项？').then(function() {
        return delProductionOrder(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/ProductionOrder/export', {
        ...this.queryParams
      }, `ProductionOrder_${new Date().getTime()}.xlsx`)
    }
  }
};


// ID生成
function generateUniqueId(existingIds) {
  const prefix = '23';
  const length = 19 - prefix.length;
  const characters = '0123456789';
  let uniqueId;

  do {
    uniqueId = prefix;
    for (let i = 0; i < length; i++) {
      uniqueId += characters.charAt(Math.floor(Math.random() * characters.length));
    }
  } while (existingIds.includes(uniqueId));

  return uniqueId;
}


//单号生成
function getOrderCode(list) {
  var date = new Date(),
    year = date.getFullYear(),
    month = date.getMonth() + 1, // 月份是从0开始的
    day = date.getDate();

// 如果月份或日期是个位数，在前面补0
  month = month < 10 ? '0' + month : month;
  day = day < 10 ? '0' + day : day;

  var time=year + '' + month + '' + day

  let type="SCGD";
  var code=time+'0000000'
  var str1=code.slice(0,7)
  var str2=code.slice(7,)

  if (str2.slice(0,1)=="0"){
    str1=code.slice(0,6)
    str2=code.slice(6,)

    for (var i=0;i<list.length;i++){
      let listCode=list[i].code.slice(4,);
      if (listCode.slice(0, 8)===time){
        if (parseInt(listCode.slice(6,))>parseInt(str2)){
          code=listCode;
          str2=code.slice(6,)
        }
      }
    }
  }else {
    for (var i=0;i<list.length;i++){
      console.log(list);
      let listCode=list[i].code.slice(4,);
      if (listCode.slice(0, 8)===time){
        if (parseInt(listCode.slice(7,))>parseInt(str2)){
          code=listCode;
          str2=code.slice(7,)
        }
      }
    }
  }

  code=type+str1+(parseInt(str2)+1)

  return code.toString();
}
</script>
